<!doctype html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
<title> WebRTC BroadCast </title>
<style type="text/css">
</style>

<script type='text/javascript'>


window.localStorage.setItem('debug', '*ERROR*');


function init() {

    
    var video_container = document.getElementById('video_container');
    var watch_url = document.getElementById('watch_url');

    const pc = new RTCPeerConnection({
        bundlePolicy: "max-bundle",
        rtcpMuxPolicy : "require"
    });

    var currentStream;
    let url = new URL(window.location);

    const socket = new WebSocket('ws://localhost:8000/channel');

    socket.onopen =  async () => {

        const constraints = {
            video: {width: {exact: 640}, height: {exact: 480}},
            audio: true
        }

        const stream = await navigator.mediaDevices.getUserMedia(constraints);

        stream.getTracks().forEach(track => pc.addTrack(track, stream));

        playVideo(stream);

        currentStream = stream;
        const offer = await pc.createOffer()
        await pc.setLocalDescription(offer)

        socket.send(JSON.stringify({
            cmd: 'publish',
            sdp: offer.sdp
        }));
    }

    socket.onmessage  = async (event) =>{
        var data = JSON.parse(event.data);
        console.log(data);

        if (data.sdp) {
            //Create answer
            const answer = new RTCSessionDescription({
                type	:'answer',
                sdp	: data.sdp
            }); 
            console.debug(answer.sdp);
            await pc.setRemoteDescription(answer); 

            watch_url.innerHTML = url.origin + "/watch/" + currentStream.id
        }
    }
}

function playVideo(stream) {
	let element = document.createElement('video');
	video_container.appendChild(element);
	element.id = 'remote_video';
	element.width = 640;
    element.height = 480;
    element.setAttribute('playsinline', true);
    element.setAttribute('autoplay', true);
	element.srcObject = stream;
    element.controls = false;
    element.muted = true;
}

</script>
</head>
<body onload="init();">
    <h1> WebRTC BroadCast</h1>

    
	<br/>
	<div id="conference">
		Video:
		<br />
		<div id="video_container">
        </div>
    </div>

    <div id="watch_url">
        
    </div>
</body>
</html>